const request = require('request');

console.log(process.env)

// let BaseUrl = "http://www.biyibibaoxian.com/server/";
let BaseUrl = "http://192.168.27.254:8088/";

function ajax(method, params) {

    let httpData = {
        headers: {}
    };

    let url = params.isSelfUrl ? params.url : BaseUrl + params.url;

    let
        successFn = params.success, // 成功回调
        errorFn = params.error,
        sendData = params.data || {}, // 请求携带的数据
        contentType = params.contentType || "application/json;charset=UTF-8", // 内容类型，决定接收方以什么形式，什么编码读取这个文件
        token = sendData.token;

    delete sendData.token

    /**
     * 处理发送的数据 
     */
    if (["GET", "DEL"].indexOf(method) > -1) { // get请求需要把参数放到 params字段里面

        url += "?"
        let arr = [];

        for (var i in sendData) {
            arr.push(i + "=" + sendData[i])
        }

        url += arr.join("&")

    } else if (["POST", "PUT"].indexOf(method) > -1) { // post 请求需要把参数放到 data 字段里面

        httpData.body = sendData
    }

    httpData.url = url;
    httpData.json = true;
    httpData.method = method;
    httpData.headers.ContentType = contentType;
    httpData.headers.Accept = "*/*";
    httpData.headers.Authorization = "Bearer " + token;

    console.log("\n\n发送请求-------------->\n\n", url, " \n data-----\n\n", sendData, "\n\n")

    request(httpData, function (error, response, body) {

        let code = response.statusCode

        if (!error && code == 200 || code == 201) {

            successFn && successFn(response)

        } else {
            errorFn && errorFn(response.body)
        }
    });
}


export let req = {
    get(data) {
        ajax("GET", data)
    },
    post(data) {
        ajax("POST", data)
    },
}